package ink.lovejinhu.interview;

import java.util.*;

/**
 * @Author: jin
 * @ClassName: Person
 * @Date: 2021/8/19 19:16
 * @Version: V1.0
 **/
public class Hw01 {
//    public static void main(String[] args) {
//        Hw01 hw01 = new Hw01();
//        int[] arr1 = {2, 3, 4, 3, 2, 1,2,3,98,100};
//        int[] arr2 = {3, 2,4,5,6,8};
//        int[] ints = hw01.sortByarr2(arr1, arr2);
//        for (int i = 0; i < ints.length; i++) {
//            System.out.print(ints[i] + " ");
//        }
//    }

    /**
     * 给你两个数组，arr1 和 arr2，arr2 中的元素各不相同。arr2 中的每个元素都出现在 arr1 中。对 arr1 中的元素进行排序，使 arr1 中项的相对顺序和 arr2 中的相对顺序相同。未在 arr2 中出现过的元素需要按照升序放在 arr1 的末尾。
     * 示例：
     * 输入：arr1 = [2,3,4,3,2,1], arr2 = [3,2]
     * 输出：[3,3,2,2,1,4]
     */
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
        ArrayList<MyMap> myMaps = new ArrayList<>();//key为arr[i]   value为在arr2中的相对位置
        LinkedList<Integer> v1 = new LinkedList<>();   //存不在arr2中
        for (int i = 0; i < arr1.length; i++) {
            if (this.isContain(arr2, arr1[i]) == -1) {   //不包含arr2
                v1.add(arr1[i]);
            } else {
                MyMap myMap = new MyMap();
                myMap.arr = arr1[i];
                myMap.location = this.isContain(arr2, arr1[i]);
                myMaps.add(myMap);
            }
        }
        Collections.sort(myMaps, new Comparator<MyMap>() {
            @Override
            public int compare(MyMap o1, MyMap o2) {
                return o1.location - o2.location;
            }
        });
        Collections.sort(v1);
        for (int i = myMaps.size() - 1; i >= 0; i--) {
            v1.addFirst(myMaps.get(i).arr);
        }
        int[] res = new int[v1.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = v1.get(i);
        }
        return res;
    }

    public int isContain(int[] arr2, int param) {
        for (int i = 0; i < arr2.length; i++) {
            if (arr2[i] == param) {  //包含
                return i;   //
            }
        }
        return -1;
    }

    class MyMap {
        int arr;
        int location;

        public int getArr() {
            return arr;
        }

        public void setArr(int arr) {
            this.arr = arr;
        }

        public int getLocation() {
            return location;
        }

        public void setLocation(int location) {
            this.location = location;
        }
    }
}
